const { default: Toast } = require("../../../dist/toast/toast");

// packageH/newDraw/components/yz_addressList/yz_addressList.js
const app = getApp();
Component({
  addGlobalClass: true,
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      value: false,
      type: Boolean
    },
    dispatch: {
      value: '',
      type: Number
    },
    need_lat :{
      value: '',
      type: Number
    },
    status: {
      value: '',
      type: Number
    },
    polygons: {
      value: [],
      type: Array
    },
    goodsStyle:{
      value:true,
      type:Boolean
    },
    confirmBtn:{
      value:true,
      type:Boolean
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    addressData: [],
    form: {},
    create: true,
    popAddAddress: false,
    addressName: {},
    districtVal: '',
    strShow: false,
    provinceData: [],
    pickerValue: [0, 0, 0],
    delivery_status: 0,
    selected: '',
    is_point: "",
    mapshow: false,
    tapEditOrAdd: 1,
    region_hide: 0,
    isclick:0,
    add_address:true,
    country_code: 0,
    addressCodeHospital:false,
    HospitalForm:{},
    chainStore:false,
  },
  lifetimes:{
    attached: function() {
      // 在组件实例进入页面节点树时执行
      console.log("在组件实例进入页面节点树时执行")
      this.triggerEvent('childShowRead')
    },
  },
  pageLifetimes: {
    show: function () {
      // this.getAddress();
      console.log('加载地址数据初始化')
      //加载地址数据初始化
      this._initAddressInfo();
      this.getIsOpenAddress();
      let yz_basic_info = wx.getStorageSync("yz_basic_info");
      this.setData({
        address_parse_open:yz_basic_info.plugin_setting.address_parse_open?yz_basic_info.plugin_setting.address_parse_open:0,
        country_code: yz_basic_info.home.system.country_code?yz_basic_info.home.system.country_code:false
      })
      console.log('xpc aa',this.data.country_code)
    },
  },

  observers: {
    'show':function(acs){
      let that = this;
      if(acs ==  true){
        that.getAddress();
        that.getIsOpenAddress();//新增地址 本地处理
      }
    },
    'dispatch': function (patch) {
      this.setData({
        delivery_status: patch
      });
    },
    'status': function (num) {
      this.setData({
        selected: num
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    tapSelect(e){
      let item = e.currentTarget.dataset.item;
      let ind = this.data.level - 1;
      if(this.data.level == 4){
        this.data.HospitalForm[this.data.level]={};
        this.data.HospitalForm[this.data.level].id = item.id;
        this.data.model.id = item.id;
        this.data.model.plugin_data[ind].value = item.room_no;
        this.data.model.plugin_data[this.data.level].value = item.department;
      }else{
        this.data.model.plugin_data[ind].value = item.name;
        this.data.HospitalForm[this.data.level]={};
        this.data.HospitalForm[this.data.level].id = item.id;
      }
      
      this.setData({
        HospitalForm:this.data.HospitalForm,
        model:this.data.model
      })
    },
    confirmTapBtn(){
      if(!this.data.model.id) return app.tips('请选择详细地址')
      let json ={
        address_id:this.data.model.id,
        user_name:this.data.form.username,
        mobile:this.data.form.mobile,
        is_default:this.data.model.isdefault
      }
      let urlStr = app.getNetAddresss("plugin.address-code.frontend.index.set-hospital");
        app._getNetWork({
          url: urlStr,
          data:json,
          success: (resdata)=> {
            var res = resdata.data;
            if (res.result == 1) {
              console.log(res,'resdata')
              this.triggerEvent('closeChild')
            }else{
              app.tips(res.msg)
            }
          },
          fail: function (res) {
            reject(res)
          }
        });
    },
    onClickRight(){
      this.setData({
        addressCodeHospital:false,
        addressCodeInfo:[]
      })
    },
    tapSearch(e){
      let level = e.currentTarget.dataset.ind + 1;
      this.setData({
        level
      })
      let json = {
        level
      }
      if(level > 1){
        if(!this.data.HospitalForm[level -1]){
          return app.tips(`请先选择${this.data.model.plugin_data[e.currentTarget.dataset.ind - 1].name}`)
        }
        json.pid = this.data.HospitalForm[level -1].id;
      }
      let urlStr = app.getNetAddresss("plugin.address-code.frontend.index.search-hospital");
        app._getNetWork({
          url: urlStr,
          data:json,
          success: (resdata)=> {
            var res = resdata.data;
            if (res.result == 1) {
              if(level != 4){
                this.setData({
                  addressCodeInfo:res.data.list,
                  addressCodeHospital:true
                })
              }else if(level == 4){
                this.setData({
                  addressCodeInfo:res.data.list,
                  addressCodeHospital:true
                })
              }
            }
          },
          fail: function (res) {
            reject(res)
          }
        });
      console.log(level)
    },
    tapToParse(){
      this.setData({
        popAddAddress:false,
        address_parse_show:true
      })
    },
    address_parseClose(e){
      console.log(e);
      this.setData({
        address_parse_show:false,
        popAddAddress:true
      })
    },
    toPostMethod(e){
      let einfo = e.detail;
      this.setData({
        'form.address':einfo.address,
        'form.province':einfo.province,
        'form.city':einfo.city,
        'form.district':einfo.region,
        'form.username':einfo.name,
        'form.mobile':einfo.mobile,
        'form.country_code':einfo.country_code,
        addressName:`${einfo.province}${einfo.city}${einfo.region}`
      })
      this._getStreet(einfo.region_id,einfo.street);
      // if(this.data.strShow){
      //   this.setData({
      //     street : einfo.street
      //   })
      // }
      this.address_parseClose();
    },
    getDefaultAddress(){
      return new Promise((resolve, reject) => {
        let that = this;
        let urlStr = app.getNetAddresss("plugin.address-code.frontend.index.get-user-info");
        app._getNetWork({
          url: urlStr,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              let info = res.data;
              info.id = 0;
              resolve(info)
            }
          },
          fail: function (res) {
            reject(res)
          }
        });
      })
    },
    //获取收货地址
    getAddress() {
      this.addressData = [];
      let that = this;
      let urlStr = app.getNetAddresss("member.member-address.index");
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let defaultAddress = res.data;
            defaultAddress = res.data.filter(function (item) {
              return item.isdefault === 1;
            });
            console.log(res.data,'ddddddddd')
            that.setData({
              popupSpecs: true,
              addressData: res.data,
              defaultAddress: defaultAddress
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    showLocation() {
      this.setData({
        mapshow: true
      });
      if(this.data.chainStore){
        let wapmap = this.selectComponent('#wapmap');
        console.log(wapmap)
        wapmap.setData({
          tag:'chainStore'
        })
      }
    },
    goLocation_ro() {
      app.getGeocoder(this.data.addressName+this.data.form.address).then(res=>{
        res = app.qqMapTransBMap(parseFloat(res.lng), parseFloat(res.lat));
        this.setData({
          is_point: res,
        });
      },err=> {
        this.showLocation();
      }).catch((err)=> {
        this.showLocation();
      });
    },
    selectAddress(e) {
      let item = e.currentTarget.dataset.addr;
      this.triggerEvent('confirm', item);
    },
    confirmSelect(e) {
      if (e.detail == 'noshow') {
        this.setData({
          mapshow: false
        });
      } else {
        let loc = e.detail;
        loc = app.qqMapTransBMap(parseFloat(loc.lng), parseFloat(loc.lat));
        if(this.data.chainStore){
          let {detail} = e;
          console.log(e)
          console.log(detail)
          this.data.form.pos.latitude = detail.lat;
          this.data.form.pos.longitude = detail.lng;
          this.data.form.pos.address = detail.address;
          this.setData({
            mapshow:false,
            'form.pos':this.data.form.pos
          })
          return
        }
        this.setData({
          is_point: loc,
          mapshow: false
        });
      }

    },
    // 地址二维码编辑的回显
    code_editAddress(e){
      let item = e;
      console.log(e,'dddddddddddd1')
      this.setData({
        "form.address_id": item.id,
        "form.username": item.username || item.user_name,
        "form.mobile": item.mobile,
        "form.province": item.province,
        "form.city": item.city,
        "form.district": item.district,
        "form.address": item.address,
        "form.street": item.street,
        "form.country_code": item.country_code,
        "form.isDefault": item.isdefault === 0 ? false : true,
        'is_point.lng': item.longitude,
        'is_point.lat': item.latitude,
        tapEditOrAdd: 1,
        model:item
      });
      console.log(this.data.form,'dddddddddddd1')
      // this.triggerEvent('confirm', this.data.for);
      this.setData({
        create: false,
        codeEdit: true,
      });
      if(item.district_id){
        this._getStreet(item.district_id);
      }
      this.setData({
        addressName: this.data.form.province + " " + this.data.form.city + " " + this.data.form.district
      });
    },
    editAddress(e) {
      let item = e.currentTarget.dataset.item;
      console.log("xpc",item)
      this.setData({
        "form.address_id": item.id,
        "form.username": item.username,
        "form.mobile": item.mobile,
        "form.province": item.province,
        "form.city": item.city,
        "form.district": item.district,
        "form.address": item.address,
        "form.street": item.street,
        "form.country_code": item.country_code,
        "form.isDefault": item.isdefault === 0 ? false : true,
        'is_point.lng': item.longitude,
        'is_point.lat': item.latitude,
        tapEditOrAdd: 1,
        model:item
      });
      if(this.data.chainStore){
        this.data.form.pos={};
        this.data.form.pos.latitude = item.latitude;
        this.data.form.pos.longitude = item.longitude;
        this.data.form.pos.address = item.position_address;
        this.setData({
          'form.pos':this.data.form.pos
        })
        this._initAddressInfo();
        this.getIsOpenAddress();
        let yz_basic_info = wx.getStorageSync("yz_basic_info");
        this.setData({
          address_parse_open:yz_basic_info.plugin_setting.address_parse_open?yz_basic_info.plugin_setting.address_parse_open:0,
          country_code: yz_basic_info.home.system.country_code?yz_basic_info.home.system.country_code:false
        })
      }
      // this.triggerEvent('confirm', this.data.for);
      this.setData({
        create: false,
        popAddAddress: true,
      });
      this._getStreet(item.district_id);
      this.setData({
        addressName: this.data.form.province + " " + this.data.form.city + " " + this.data.form.district
      });

    },
    //关闭增加地址
    popAddressClose() {
      this.setData({
        popAddAddress: false
      });
    },
    countryCodeInput: function (e) {
      let value = e.detail.value;
      this.setData({
        "form.country_code": value,
      });
    },
    //收件人输入绑定
    usernameinp: function (e) {
      let nameval = e.detail.value;
      this.setData({
        "form.username": nameval
      });
    },
    //联系电话输入绑定
    mobileinp: function (e) {
      let mobileval = e.detail.value;
      this.setData({
        "form.mobile": mobileval
      });
    },
    //默认地址开关值绑定
    isDefaultChange: function (e) {
      let isDefault = e.detail;
      this.setData({
        "form.isDefault": isDefault
      });
    },
    //详细地址绑定输入
    addressinp: function (e) {
      let addressval = e.detail.value;
      this.setData({
        "form.address": addressval
      });
    },
    // 关闭选择收货地址
    _closeDateLw: function () {
      this.setData({
        openDateLw: false
      });
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = 'provinceData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          console.log("地址信息准备就绪");
          that._getProvinceData();
        },
        fail: function (res) {
          console.log("省fail");
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: 'provinceData',
                data: province
              });
              wx.setStorage({
                key: 'cityData',
                data: city
              });
              wx.setStorage({
                key: 'districtData',
                data: district
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true
          });
        }
      });
    },
    // 读取省key
    _getProvinceData: function () {
      var that = this;
      var _keyName = 'provinceData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("省读取成功", res.data);
          that.setData({
            provinceData: res.data
          });
          that.setData({
            "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
            "selectAddressData[0].index": that.data.pickerValue[0]
          });
          that._getCityData();
        }
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      // console.log("城市", "_data", _data);
      var that = this;
      var _keyName = 'cityData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("城市读取成功", res);

          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("城市数据筛选", _json);
          that.setData({
            cityData: _json
          });
          that.setData({
            "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1]
          });
          that._getDistrictData();
        }
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      // console.log("地区", "_data", _data)
      var that = this;
      var _keyName = 'districtData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          console.log("地区读取成功");
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("地区数据筛选", _json);
          that.setData({
            districtData: _json
          });
          // console.log("districtData", _json);
          that.setData({
            "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2]
          });
          // console.log("over", that.data.selectAddressData);
        }
      });
    },
    //打开地址选择器
    openDateLwtbtn: function () {
      this.setData({
        openDateLw: true
      });
      if(!this.data.goodsStyle){
        this._initAddressInfo();
      }
      console.log('aaaaaaaaaaaaaaa')
    },
    // 收货地址滚动事件
    bindChange: function (e) {
      var val = e.detail.value;
      if (this.data.pickerValue[0] != val[0]) {
        val[1] = 0;
        val[2] = 0;
      }
      if (this.data.pickerValue[1] != val[1]) {
        val[2] = 0;
      }
      this.setData({
        "pickerValue[0]": val[0],
        "pickerValue[1]": val[1],
        "pickerValue[2]": val[2]
      });
      this._initAddressInfo();
    },
    // 确定选择收货地址
    _okAddress: function () {
      let seleData = this.data.selectAddressData;
      this.setData({
        "form.street": "",
        "districtVal": "",
        "addressName": seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
        "form.province": seleData[0].name,
        "form.city": seleData[1].name,
        "form.district": seleData[2].name
      });
      this._getStreet(seleData[2].id);
      this._closeDateLw();
    },
    //获取街道
    _getStreet(param,key = '') {
      let that = this;
      let urlStr = app.getNetAddresss("member.memberAddress.street");
      urlStr += "&district_id=" + param;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1 && !app._isTextEmpty(res.data)) {
            if (!app._isTextEmpty(res.data) && res.data.length > 0) {
              that.setData({
                districtVal: res.data,
                strShow: true
              });
              if(key){
                that.setData({
                  'form.street':key
                })
              }
            } else {
              that.setData({
                strShow: false
              });
            }
          } else {
            that.setData({
              strShow: false
            });
          }
        },
        fail: function (res) {
          that.setData({
            strShow: false
          });
          console.log(res);
        }
      });
    },
    streetChoose() {
      if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
        wx.showToast({
          icon: 'none',
          title: '请先选择所在地区',
          duration: 1500
        });
      } else {
        this.setData({
          streetShow: true,
          opren: false
        });
      }
    },
    //关闭选择街道弹窗
    streetClose: function () {
      this.setData({
        streetShow: false,
        opren: true
      });
    },
    //选择街道
    streetConfirm(e) {
      let strname = e.target.dataset.strname;
      this.setData({
        "form.street": strname,
        "streetShow": false,
        opren: true
      });
    },
    //增加地址
    appendAddress(e) {
      let that = this;
      let apptype = e.currentTarget.dataset.apptype;
      if (app._isTextEmpty(this.data.form.country_code) && this.data.country_code) {
        wx.showToast({
          icon: "none",
          title: "请输入区号",
          duration: 1500,
        });
        return;
      }
      if (app._isTextEmpty(this.data.form.username)) {
        wx.showToast({
          icon: 'none',
          title: "请输入收货人姓名",
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.form.mobile)) {
        wx.showToast({
          icon: 'none',
          title: "请输入联系电话",
          duration: 1500
        });
        return;
      }
      if (!/^[0-9]{1,}$/.test(this.data.form.mobile)) {
        wx.showToast({
          icon: 'none',
          title: "请输入联系电话",
          duration: 1500
        });
        return;
      }
      if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
        wx.showToast({
          icon: 'none',
          title: "请选择所在区域",
          duration: 1500
        });
        return;
      }
      // 优化#93791
      // if (this.data.is_region == 1 && this.data.strShow && app._isTextEmpty(this.data.form.street)) {
      //   wx.showToast({
      //     icon: 'none',
      //     title: "请选择所在街道",
      //     duration: 1500
      //   });
      //   return;
      // }
      if (app._isTextEmpty(this.data.form.address)) {
        wx.showToast({
          icon: 'none',
          title: "请输入详细地址",
          duration: 1500
        });
        return;
      }
      if(this.data.isclick == 1){
        return
      }
      this.data.isclick = 1;
      let json = {};
      json = {
        username: this.data.form.username,
        mobile: this.data.form.mobile,
        province: this.data.form.province,
        city: this.data.form.city,
        district: this.data.form.district,
        address: this.data.form.address,
        isdefault: this.data.form.isDefault ? 1 : 0,
        address_id: this.data.form.address_id
      };
      if (this.data.is_point) {
        json.longitude = this.data.is_point.lng;
        json.latitude = this.data.is_point.lat;
      }
      if (this.data.strShow) {
        json.street = this.data.form.street;
      }
      // 连锁店 新增传参
      if (this.data.chainStore){
        json.longitude = this.data.form.pos.longitude;
        json.latitude = this.data.form.pos.latitude;
        json.position_address = this.data.form.pos.address;
      }
      if(this.data.country_code) json.country_code =  this.data.form.country_code;
      let urlStr = '';
      if (apptype === 'update') {
        urlStr = app.getNetAddresss('member.member-address.update');
      } else {
        urlStr = app.getNetAddresss('member.member-address.store');
      }
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: (resdata)=> {
          var res = resdata.data;
          setTimeout(() => {
            this.data.isclick = 0
          }, 1000);
          if (res.result == 1) {
            if(!this.data.codeEdit){
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
              that.triggerEvent('confirm', res.data);
              that.popAddressClose();
              that.setData({
                "form.username": '',
                "form.mobile": '',
                "form.province": '',
                "form.city": '',
                "form.district": '',
                "form.street": '',
                "form.address": '',
                "form.isDefault": false,
                "form.country_code": '86',
                addressName: '',
              });
            }else{
              that.triggerEvent('confirm', res.data);
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          wx.showToast({
            icon: 'none',
            title: '接口报错',
            duration: 1500
          });
        }
      });
    },
    onCloseAdd() {
      this.setData({
        show: false
      });
    },
    //跳转到新增地址
    addAddress() {
      this.setData({
        is_point: '',
        tapEditOrAdd: 2
      });
      //新增地址 本地处理
      this.showAddAddress();
    },
    getIsOpenAddress() {
      var that = this;
      let urlStr = app.getNetAddresss("member.member-address.is-region");
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1 && !app._isTextEmpty(res.data)) {
            that.setData({
              is_region: res.data.is_region,
              region_hide: res.data.region_hide //是否隐藏所在地区
            });
          } else {
            console.log(res.msg);
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    //显示增加地址
    showAddAddress(key = '') {
      this.setData({
        "form.username": '',
        "form.mobile": '',
        "form.province": '',
        "form.city": '',
        "form.district": '',
        "form.street": '',
        "form.address": '',
        "form.isDefault": false,
        "form.country_code": '86',
        addressName: '',
        popAddAddress: true,
        create: true,
        model:{}
      });
      if(this.data.chainStore){
        this.setData({
          "form.pos":{}
        })
        this._initAddressInfo();
        this.getIsOpenAddress();
        let yz_basic_info = wx.getStorageSync("yz_basic_info");
        this.setData({
          address_parse_open:yz_basic_info.plugin_setting.address_parse_open?yz_basic_info.plugin_setting.address_parse_open:0,
          country_code: yz_basic_info.home.system.country_code?yz_basic_info.home.system.country_code:false
        })
        return
      }
      if(!key && this.data.defaultAddress.length <=0){
        // 如果地址列表里面没有默认的地址就把默认按钮设为true  优化任务#94289
        this.setData({
          "form.isDefault": true,
        })
      }
      if(this.data.tapEditOrAdd == 2 && !this.data.goodsStyle){
        this.setData({
          "form.isDefault": true,
        })
      }
    },
  }
});
